<?php
class Admin_configureController extends Controller {
    /**
     * 定义布局视图
     * 
     * @var string
     */
    protected function before() {
	
		$this->set_layout('admin_main');
	}
    
    /**
     * 后台管理：常规设置页面
     */
	public function indexAction() {
         //判断登陆
        auth::parse_login();
        
        $db_cache = $this->instance('cache_db');
        $config_data = $db_cache->load_config('config_options', 'option_name', 'option_value');               
        
        //assign params
        $this->assign(array(
            'site_name'     => '常规设置',
            'config_data'   => $config_data,
        ));
            
        //display page
        $this->display();
	}
    
    /**
     * AJAX处理常规设置
     */
    public function ajax_common_submitAction() {
         //判断登陆
        auth::parse_login(true);
        
       //get params
        $site_name          = $this->post('site_name');
        $site_description   = $this->post('site_description');
        $meta_keyword       = $this->post('meta_keyword');
        $meta_description   = $this->post('meta_description');
        
        //instance model
        $config_model = $this->model('config_options');
        
        $update_array = array(
            'site_name'         => $site_name,
            'site_description'  => $site_description,
            'meta_keyword'      => $meta_keyword,
            'meta_description'  => $meta_description,
        );
        
        //调用config model类的自定义函数config_update();
        echo $config_model->config_update($update_array) ? 101 : 100;         
    }
    
    /**
     * AJAX处理文章设置
     */
    public function ajax_articleAction() {
         //判断登陆
        auth::parse_login(true);
       
       //get params
        $list_num = $this->post('list_num');
        
         //instance model
        $config_model = $this->model('config_options');
        
        //调用config model类的自定义函数config_update();
       echo $config_model->config_update(array('max_list_num'=>$list_num)) ? 101 : 100;
    }

    /**
     * 后台管理：文章设置页面
     */
    public function articleAction()	{
         //判断登陆
        auth::parse_login();
        
        $db_cache = $this->instance('cache_db');
        $config_data = $db_cache->load_config('config_options', 'option_name', 'option_value');
        
        //assign params
        $this->assign(array(
            'site_name'     => '文章设置',
            'config_data'   => $config_data,
        ));
            
        //display page
        $this->display();
    }

    /**
     * 后台管理：评论设置页面
     */
    public function commentAction() {
         //判断登陆
        auth::parse_login();
        
        $db_cache = $this->instance('cache_db');
        $config_data = $db_cache->load_config('config_options', 'option_name', 'option_value');
        
        //assign params
        $this->assign(array(
            'site_name' => '评论设置',
            'config_data'   => $config_data,
        ));
            
        //display page
        $this->display();
    }
    
    /**
     * AJAX处理comment
     */
    public function ajax_commentAction() {
        //判断登陆
        auth::parse_login(true);
       
       //get params
        $status= (int)$this->post('status');
        
         //instance model
        $config_model = $this->model('config_options');
        
        //调用config model类的自定义函数config_update();
       echo $config_model->config_update(array('is_verify'=>$status)) ? 101 : 100;
    }

        /**
     * 数据恢复与备份
     */
    public function dataAction() {
         //判断登陆
        auth::parse_login();
        
        $mode = (int)$this->get('mode');
        
        //assign params
        $this->assign(array(
            'site_name' => '数据',
            'mode'      => $mode,
        ));
            
        //display page
        $this->display();
    }
    
    /**
     * 导出数据
     */
    public function exportAction() {
        //判断登陆
        auth::parse_login();
        
        set_time_limit(0);
        
        //所要备份的数据表列表
        $table_array = array(
          'admin_users',
          'comments',
          'config_options',
          'friend_links',
          'posts',
          'post_meta',
          'post_tags',
          'tags',
          'terms',
          'words', 
        );
        
        $sql_str = '';
		foreach ($table_array as $table_name){
			$sql_str .= $this->handle_create_table($table_name);
			$sql_str .= $this->handle_table_data($table_name);
		}
        
		//zip load..
		$zip = $this->instance('zip');
		$zip->add_file($sql_str, 'SmileBlogDate.sql');
		$zip->download('SmileBlogDate'.date('Y-m-d', time()));
    }
    
    //处理新建数据表的sql语句
	protected function handle_create_table($table_name){
		//参数判断
		if(!$table_name){
			return false;
		}
        
		//实例化model
		$model = $this->model($table_name);	
        
		$sql_str = "DROP TABLE IF EXISTS {$table_name};";
		$data = $model->execute('SHOW CREATE TABLE ' . $table_name, false);
        
		//返回数据	
		return empty($data) ? false : $sql_str . trim($data['Create Table']) . ';';		
	}
    
    //处理数据表的数据备份
	protected function handle_table_data($table_name){
		//参数判断
		if(!$table_name){
			return false;
		}
        
		//实例化model
		$model = $this->model($table_name);
        
		//获取数据表数据信息
		$fields_data = $model->execute('SHOW FIELDS FROM ' . $table_name, true, true);        
		if ($fields_data == false){
			return false;
		}
        
		$fields_array = array();
		foreach ($fields_data as $lines){
			$fields_array[] = '`' . $lines['Field'] . '`';
		}
        
		$sql_str = 'INSERT INTO ' . $table_name . ' (' . implode(',', $fields_array) . ') VALUES';
		
		$list_data = $model->from($table_name)->select();
		if ($list_data == false){
			return false;
		}
		$total_rows_num = sizeof($list_data);
		foreach ($list_data as $key=>$lines){
			$sql_str .= '(';
			$fields_data_array = array();
			foreach ($lines as $value){
				$fields_data_array[] = ($value === null) ? 'null' : $model->quote_into($value);
			}
			$sql_str .= implode(',', $fields_data_array);
			$sql_str .= ($key + 1 == $total_rows_num) ? ');' : '),';
		}
		return $sql_str;
	}
    
    /**
     * 恢复数据
     */
    public function importAction() {
        //判断登陆
        auth::parse_login();
        
        //判断上传文件的格式
		if(isset($_FILES['db_file']) == false) {
			exit();
		}
        
		$db_data = $_FILES['db_file']['tmp_name'];
        //$this->dump($_FILES['db_file']);
		switch ($_FILES['db_file']['type']) {            
			case 'application/x-zip-compressed':
            case 'application/zip':
            case 'application/octet-stream':    
				$zip = $this->instance('zip');                 
				$zip_content = $zip->read_zip($db_data);
				$content = $zip_content[0]['data'];               
				break;
            
			case 'text/plain':
				$content = file_get_contents($db_data);
				break;	
		}
        
		//实例化model.
		$model = $this->model('posts');
        
		if($content) {
			$sql_list_array = explode(';', $content);
			$result_state = false;
			foreach ($sql_list_array as $lines) {
				if(empty($lines)) {
					continue;
				}else {
					if($model->execute($lines)) {
						$result_state = true;
					} else {
						$result_state = false;
						break;
					}
				}
			}			
			
			echo ($result_state == true) ? 101 : 100;
		}
    }
}